<?php

namespace app\manage\controller; 

use core\libs\db;
use core\libs\input;
use core\libs\log;

class login extends \core\libs\controller {
    public function index() {
        if(input::session("admin__name")) {
            jump("/manage/index");
        }
        $this->display("login");
    }
    public function sign() {
        extract(
            input::request('validator', 'username', 'password', 'language')
        );
        
        if(strcasecmp($validator, input::session("CAPTCHA")) != 0)	{
            exit(alert('错误：验证码不正确！', '/manage/login'));
        }

        if(!isset($username) || !isset($password)) {
            log::insert('登录失败：用户名或密码不能为空', "manage/");
            exit(alert('错误：用户名或密码不能为空！', '/manage/login'));
        }

        if(!$language)	{
            exit(alert('错误：请选择语言！', '/manage/login'));
        }
        db::$table_prefix = $language . "_"; // 设置数据表前缀
        
        $password = md5($password);
        $row = db::fetch('admin', "username = '$username' and password = '$password'", 'id');
        if($row) {
            //管理员帐号							
			$_SESSION["admin__name"] = $username; 
            //管理员帐号							
			$_SESSION["admin__language"] = $language;
			//管理员ID
			$_SESSION["admin__id"]   = $row['id'];  
			//更新登录IP与次数	
            db::update('admin', array('ip' => get_real_ip(), 'num' => 'num+1'), "id = '$row[id]'");
            // 跳转到首页
            jump("/manage/index");
        }
        else {
            log::insert('登录失败：用户名或密码错误', "manage/");
			exit(alert("错误：用户名或密码不正确！", '/manage/login'));
        }
    }
    public function logout() {
        session_destroy();
		echo "<script>window.parent.location.href='/manage/login', '_blank';</script>";
    }
}